package com.yudaxian.interceptor;

import com.alibaba.fastjson2.JSON;
import com.yudaxian.common.util.JwtUtil;
import com.yudaxian.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j  // 日志
public class JwtValidateInterceptor implements HandlerInterceptor {

    @Resource
    private JwtUtil jwtUtil;

    /***
     * jwt验证拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 拿到token，然后进行验证

        String token = request.getHeader("X-Token");
        // XX请求需要验证token
        log.debug(request.getRequestURI() + "需要验证" + token);

        if (token != null) {
            try {
                jwtUtil.parseToken(token);
                // XX请求验证通过token
                log.debug(request.getRequestURI() + "验证通过" + token);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.debug(request.getRequestURI() + "验证失败，禁止访问");

        Result<Object> fail = Result.fail(20003, "JTW无效，请重新登录");

        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(fail));

        // 拦截，禁止通行
        return false;
    }
}
